# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from common.db_model_fields import ListField
from common.menum import MEnum
from common.share_mem import ShareMem
from common.types import TYPE_INT, TYPE_FLOAT, TYPE_STR, TYPE_NONE, TYPE_LIST

import logging
logger = logging.getLogger('bt_server')

sm = ShareMem(access=ShareMem.SHARE_MEM_ACCESS_WRITE)  # 内存共享


class BaseModel(models.Model):
    create_time = models.DateTimeField('创建时间', auto_now_add=True)
    update_time = models.DateTimeField('更新时间', auto_now=True)

    def save(self, *args, **kwargs):
        return super(BaseModel, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        if hasattr(self, 'is_delete'):
            self.is_delete = True
            return super(BaseModel, self).save()
        else:
            return super(BaseModel, self).delete(*args, **kwargs)

    class Meta:
        abstract = True


class FakeDeleteModel(BaseModel):
    is_delete = models.BooleanField('标记删除', default=False)

    def delete(self, *args, **kwargs):
        self.is_delete = True
        return super(BaseModel, self).save()

    class Meta:
        abstract = True


class BtResource(BaseModel):
    """
    资源
    """
    name = models.CharField('资源名称', max_length=200)
    category = models.CharField('文件分类 参考:settings.FOLDER_CATEGORY_PATH_DICT', max_length=200)
    torrent_file_name = models.CharField('资源对应的torrent文件名称', max_length=250)
    """enum state_t
        {
            checking_files,
            downloading_metadata,
            downloading,
            finished,
            seeding,
            allocating,
            checking_resume_data,
        };
    """
    state =  models.CharField('状态', max_length=64)
    size = models.IntegerField('大小', default=0)
    info_hash = models.CharField('torrent 信息哈希', max_length=40)
    active_time = models.IntegerField('活跃时间(s)', default=0)

    announcing_to_dht = models.BooleanField('announcing to dht', default=False)
    announcing_to_lsd = models.BooleanField('announcing to lsd', default=False)
    announcing_to_trackers = models.BooleanField('announcing to trackers', default=False)

    is_finished = models.BooleanField('是否完成', default=False)
    is_loaded = models.BooleanField('是否加载', default=False)
    is_seeding = models.BooleanField('是否在做中', default=False)

    progress = models.FloatField('完成度(0.0-1.0)', default=0.0)
    completed_time = models.DateTimeField('完成时间', blank=True, null=True)

    download_rates = ListField('下载速度(bytes/s)', max_length=1500, blank=True)
    upload_rates = ListField('上传速度(bytes/s)', max_length=1500, blank=True)
    total_download = models.IntegerField('总下载量(bytes)', default=0)
    total_upload = models.IntegerField('总上传量(bytes)', default=0)

    class Meta:
        unique_together = ('name', 'category')

    @classmethod
    def reset_all_status(cls):
        BtResource.objects.update(**{
            'active_time': 0,
            'state': 'stop',
            'download_rates': [],
            'upload_rates': [],
        });

    def peers(self):
        try:
            peers = sm.json_read()
            # logger.info(peers)
            return peers[str(self.id)]
        except Exception as e:
            logger.error(e)
            return []
